﻿



CREATE proc [setting].[SaveSetting]
@SettingID uniqueidentifier = null,
@Domäne nvarchar(50),
@SettingName nvarchar(50),
@SettingValue nvarchar(max)

as
begin
	declare @errorMsg nvarchar(150),
			@logDate datetime2(7),
			@setID nvarchar(150)

	if @SettingID is null
	begin
		set @SettingID = NEWID();
	end
	
	set @setID = cast(@SettingID as nvarchar(50))

	if @Domäne is null
	begin
		set @errorMsg = '@Domäne is null or empty.'
		goto WithError
	end

	if @SettingName is null
	begin
		set @errorMsg = '@SettingName is null or empty.'
		goto WithError
	end

	if @SettingValue is null
	begin
		set @errorMsg = '@SettingValue is null or empty.' 
		goto WithError
	end
	
	
	begin tran

	;with sel as
	(
		select 
		@SettingID		'SettingID',
		@Domäne			'Domäne',
		@SettingName	'SettingName',
		@SettingValue	'SettingValue'
	)
	merge into [setting].datSettings as t
	using sel as s on
		s.SettingID = t.SettingID
	when not matched by target then
		insert (
			SettingID,
			Domäne,
			SettingName,
			SettingValue
		)
		values (
			s.SettingID,
			s.Domäne,
			s.SettingName,
			s.SettingValue
			)
	when matched then
		update set 
			Domäne			= s.Domäne,
			SettingName		= s.SettingName,
			SettingValue	= s.SettingValue
			;
	
	commit tran
return 0

WithError:
	if @@TRANCOUNT != 0
	begin
		rollback tran
	end
	RAISERROR
    (@errorMsg,
    10, -- Severity.
    1, -- State.
    @setID, -- First substitution argument.
    @SettingName); -- Second substitution argument. 
	return -1 
end


GO
GRANT EXECUTE
    ON OBJECT::[setting].[SaveSetting] TO PUBLIC
    AS [dbo];

